using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using ContentmanagementBase.Domain;
using ContentmanagementBaseWrite.API.Applications.Commands;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace ContentmanagementBaseWrite.API.Applications.Commandhandlters
{
    /// <summary>
    /// 批量逻辑删除轮播图信息命令处理
    /// </summary>
    public class BatchDeleteCarouselCommandHandler : IRequestHandler<BatchDeleteCarouselCommand, ApiResult<bool>>
    {
        /// <summary>
        /// 轮播图仓储
        /// </summary>
        private readonly IBaseRepository<CarouelChartModel> _carouselRepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<BatchDeleteCarouselCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="carouselRepository">轮播图仓储</param>
        /// <param name="logger">日志</param>
        public BatchDeleteCarouselCommandHandler(
            IBaseRepository<CarouelChartModel> carouselRepository,
            ILogger<BatchDeleteCarouselCommandHandler> logger)
        {
            _carouselRepository = carouselRepository;
            _logger = logger;
        }

        public async Task<ApiResult<bool>> Handle(BatchDeleteCarouselCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证输入参数
                if (request.Ids == null || !request.Ids.Any())
                {
                    return new ApiResult<bool>
                    {
                        code = ResultEnumCode.fails,
                        message = "轮播图编号列表不能为空",
                        data = false
                    };
                }

                // 验证ID列表中的每个ID是否有效
                if (request.Ids.Any(id => id <= 0))
                {
                    return new ApiResult<bool>
                    {
                        code = ResultEnumCode.fails,
                        message = "轮播图编号必须大于0",
                        data = false
                    };
                }

                // 查找要删除的轮播图
                var carouselsToDelete = await _carouselRepository.GetAll()
                    .Where(x => request.Ids.Contains(x.Id) && !x.IsDeleted)
                    .ToListAsync(cancellationToken);

                if (!carouselsToDelete.Any())
                {
                    return new ApiResult<bool>
                    {
                        code = ResultEnumCode.fails,
                        message = "未找到要删除的轮播图或轮播图已被删除",
                        data = false
                    };
                }

                // 检查是否所有请求的ID都找到了
                var foundIds = carouselsToDelete.Select(x => x.Id).ToList();
                var notFoundIds = request.Ids.Except(foundIds).ToList();

                if (notFoundIds.Any())
                {
                    return new ApiResult<bool>
                    {
                        code = ResultEnumCode.fails,
                        message = $"以下轮播图不存在或已被删除：{string.Join(", ", notFoundIds)}",
                        data = false
                    };
                }

                // 执行批量逻辑删除
                var deleteTime = DateTime.Now;
                foreach (var carousel in carouselsToDelete)
                {
                    carousel.IsDeleted = true;
                    carousel.UpdatedTime = deleteTime;
                    // 可以在这里添加删除原因字段，如果模型中有的话

                }

                // 批量保存修改
                await _carouselRepository.UpdateRanger(carouselsToDelete);

                return new ApiResult<bool>
                {
                    code = ResultEnumCode.Ok,
                    message = $"成功删除 {carouselsToDelete.Count} 个轮播图",
                    data = true
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量逻辑删除轮播图过程中发生异常，删除的ID：{Ids}", 
                    string.Join(", ", request.Ids));

                return new ApiResult<bool>
                {
                    code = ResultEnumCode.fails,
                    message = $"批量删除轮播图失败：{ex.Message}",
                    data = false
                };
            }
        }
    }
} 